package com.backend.system.service.processors.menu;


import com.backend.system.beans.DeleteReq;
import com.backend.system.common.CustomException;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.Menu;
import com.backend.system.dao.entity.MenuRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 删除菜单处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.MENU_DELETE)
public class MenuDeleteProcessor extends AbstractProcessorTemplate<DeleteReq, Boolean> {

    @Override
    protected void init(ProcessorContext<DeleteReq> context) {
        DeleteReq req = context.getData();
        // 判断当前菜单是否有下一级菜单
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getParentId, req.getId());
        long count = menuService.count(queryWrapper);
        if (count != 0L) {
            throw CustomException.argsError("当前菜单存在子级菜单，不能删除");
        }

        // 菜单是否被分配到角色
        LambdaQueryWrapper<MenuRole> menuRoleQueryWrapper = new LambdaQueryWrapper<>();
        menuRoleQueryWrapper.eq(MenuRole::getMenuId, req.getId());
        long menuRoleCount = menuRoleService.count(menuRoleQueryWrapper);
        if (menuRoleCount != 0L) {
            throw CustomException.argsError("当前菜单已被分配到角色，不能删除");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<DeleteReq> context) {
        DeleteReq req = context.getData();
        return menuService.removeById(req.getId());
    }
}
